package com.fpx.order.plat.bussiness.plat.smt.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fpx.api.bean.order.Order;
import com.fpx.api.bean.request.SubmitOrderRequest;
import com.fpx.api.bean.response.ResultMessage;
import com.fpx.api.bean.response.SubmitOrderResponse;
import com.fpx.api.service.ISmtService;
import com.fpx.api.util.Constant;
import com.fpx.order.plat.bussiness.cache.CacheManage;
import com.fpx.order.plat.bussiness.entity.CustomerShop;
import com.fpx.order.plat.bussiness.entity.OriginOrder;
import com.fpx.order.plat.bussiness.plat.base.IPlatDeliveryOrderHandler;
import com.fpx.order.plat.bussiness.plat.base.SdkCommonOrderDeliverThread;
import com.fpx.order.plat.bussiness.service.order.IOriginOrderService;
import com.fpx.order.plat.bussiness.service.order.IOriginOrderitemService;
import com.fpx.order.plat.bussiness.system.CacheConstants;
import com.fpx.order.plat.bussiness.system.PlatConstants;

/**
 * SMT（速卖通）订单回传服务
 * desc: SmtDeliveryOrderHandler
 * @author xiangtao(xiangtao@4px.com)
 * @date 2015年12月8日 下午5:57:30
 * @version 1.0
 */
@Component
public class SmtDeliveryOrderHandler implements IPlatDeliveryOrderHandler{
	
	private final static Logger LOGGER = Logger.getLogger(SmtDeliveryOrderHandler.class);
	
	@Autowired
	private IOriginOrderService originOrderService;
	
	@Autowired
	private IOriginOrderitemService originOrderitemService;
	
	@Autowired
	private ISmtService smtService;
	
	@Autowired 
	private CacheManage cacheManage;
	
	@Override
	public void deliveryOrder(CustomerShop customer,int reqNum) throws Exception {
		//客户编号
		String cm_id = customer.getCm_id();
				//店铺代码
		String cs_code = customer.getCs_code();
				//获取店铺TOKEN
		String token = customer.getCs_token();
						
		SubmitOrderRequest request = new SubmitOrderRequest();
		
		Map<String,String>configMap=
				cacheManage.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_SMT);
		request.setConfigMap(configMap);
		//SMT平台的授权令牌
		request.setToken(token);
		//平台类型  SMT
		request.setPlatform(Constant.PLATFORM_SMT);
		//封装订单信息
		List<Order> orders = new ArrayList<Order>();
		//需要同步的订单集合
		List<OriginOrder> orderList = originOrderService.findDeliveryOrder(cm_id, cs_code, PlatConstants.ORDER_SOURCE_SMT);
		if(null == orderList || orderList.size() <= 0){
			LOGGER.info("【SMT】---商家【" + cm_id + "】店铺代码【"+cs_code+"】没有需要同步的订单");
			return;
		}
		for (int j = 0; j < orderList.size(); j++) {
			OriginOrder originOrder = orderList.get(j);
			if(originOrder==null){
				continue;
			}
			if(StringUtils.isEmpty(originOrder.getOrder_code())||
					StringUtils.isEmpty(originOrder.getShip_server_code())){
				continue;
			}
			Order order = new Order();
			//客户单证号
			order.setOrderNo(originOrder.getOrder_code());
			//跟踪单号（运单号）
			order.setTrackingNo(originOrder.getShip_server_code());
			//运输方式（承运商）
			if(StringUtils.isEmpty(originOrder.getShipping_service())){
				order.setShipway4px("Other");
			}else{
				order.setShipway4px(originOrder.getShipping_service());
			}
			orders.add(order);
		}
		if(orders.size()<=0){
			LOGGER.error("【SMT】---商家【" + cm_id + "】   商铺代码【"+cs_code+"】店铺封装订单参数失败");
			return ;
		}
		request.setOrders(orders);
		//获取返回结果
		SdkCommonOrderDeliverThread requestThread = new SdkCommonOrderDeliverThread(orders.size(),request,PlatConstants.ORDER_SOURCE_SMT,smtService);
		new Thread(requestThread).start();
		SubmitOrderResponse response = requestThread.getResponse();
		if(response == null){
			LOGGER.error("-----------------结束同步SMT店铺：【" + cs_code + "】已发货的销售接口表订单,请求超时.------------------------------");
			return;
		}
		List<ResultMessage> resultMessages = response.getDetailMessages();
		if(resultMessages == null || resultMessages.size() <= 0){
			LOGGER.error("-----------------结束同步SMT店铺：【" + cs_code + "】已发货的销售接口表订单,上传运单号没有返回执行结果的详情信息.------------------------------");
			return;
		}
		//同步成功更新销售接口表同步状态
		int index = 0;
		List<String> orderIds = new ArrayList<String>();
		for(ResultMessage rm : resultMessages){
			if(rm == null){
						continue;
				}
			String order_code = rm.getOrderId();
			if("SUCCESS".equals(rm.getMessage())){
				orderIds.add(order_code);
				index++;
				if(index >= 50){
					originOrderService.updateDeliveryStatusSuccess(orderIds, PlatConstants.ORDER_SOURCE_SMT);
					index=0;
					orderIds.clear();
				}
			}else{
				originOrderService.updateDeliveryStatusfailure(order_code, PlatConstants.ORDER_SOURCE_SMT, rm.getMessage());
				LOGGER.error("-----------------同步 店铺【" + order_code + "】 Ebay销售接口表订单发货异常订单号："+rm.getOrderId() + "，异常描述：" + rm.getMessage());
			}
		}
		if(index != 0){
			originOrderService.updateDeliveryStatusSuccess(orderIds, PlatConstants.ORDER_SOURCE_SMT);
		}
	}
}
